package com.ark.frigate.mybatis.dao;

import com.ark.frigate.mybatis.common.CreateFileHandle;
import com.ark.frigate.mybatis.config.StrategyConfig;
import com.ark.frigate.mybatis.utils.FileUtils;
import com.ark.frigate.mybatis.utils.TempBatisUtils;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 负责生成MyBatis的实体类、实体映射XML文件、Mapper
 *
 * @author WeiLong
 */
public class BuildHandle extends CreateFileHandle {

    private static Logger logger = LoggerFactory.getLogger(BuildHandle.class);

    private String interfaceClass = "mybatis/dao/interfaceClass.tmpe";

    public BuildHandle(StrategyConfig strategyConfig) {
        super("mybatis/dao/entityClass.tmpe", "mybatis/dao/xmlMapper.vm");
        this.strategyConfig = strategyConfig;
    }

    public BuildHandle(String entityClass, String interfaceClass, String xmlMapper) {

        super(entityClass, xmlMapper);
        if (StringUtils.isNotBlank(interfaceClass)) {
            this.interfaceClass = interfaceClass;
        }
    }

    /**
     * 构建接口映射JAVA接口 2016年11月8日 下午8:38:22
     *
     * @param beanName 类型名称
     * @param daoName  dao名称
     * @throws IOException IO异常
     */
    public void buildDao(String beanName, String daoName) throws IOException {

        Map<String, Object> paramMap = Maps.newHashMap();

        paramMap.put("DaoPackage", strategyConfig.getDaoPackage());
        paramMap.put("BeanPackage", strategyConfig.getBeanPackage() + "." + beanName);
        paramMap.put("TableComment", daoName + " 数据库操作类");
        paramMap.put("ClassName", daoName);
        paramMap.put("BeanName", beanName);
        paramMap.put("Author", strategyConfig.getAuthor());
        paramMap.put("JavaMethod", "");

        InputStream interfaceTemp = this.getClass().getClassLoader().getResourceAsStream(this.interfaceClass);
        // 读取模板
        String content = TempBatisUtils.readToTemplate(interfaceTemp, paramMap);
        // 新建一个文件
        File folder = new File(strategyConfig.getDaoPath());
        if (!folder.exists()) {
            boolean createFolder = folder.mkdirs();
            logger.info("文件创建结束，{}", createFolder);
        }
        File mapperFile = new File(strategyConfig.getDaoPath(), daoName + ".java");
        // 写入文件
        FileUtils.writeContent(mapperFile, content);
    }

}